<template>
  <el-form ref="formRef" class="form" :model="_form" :rules="rules" label-width="100px">
    <div class="top">
      <div class="top-l">
        <el-form-item label-width="0">
          <hold-upload
            :key="uploadKey"
            list-type="picture"
            :file-list="[]"
            :limit="1"
            file-name="headPhoto"
            file-type=".png,.jpg,.jpeg"
            :show-file-list="false"
            :avatar-url="_form.logo ? formatUrl(_form.logo) : ''"
            @success="handleSuccess"
          />
        </el-form-item>
      </div>
    </div>
    <el-form-item label="组织名称" prop="name">
      <el-input v-model.trim="_form.name" placeholder="请输入组织名称" />
    </el-form-item>
    <el-form-item label="社会代码" prop="cods">
      <el-input v-model.trim="_form.cods" placeholder="请输入社会代码" />
    </el-form-item>
    <el-row>
      <el-form-item label="组织类型" prop="type">
        <el-select
          ref="typeRef"
          v-model="_form.type"
          class="org-type"
          clearable
          filterable
          style="width: 100%"
          placeholder="请选择组织类型"
        >
          <el-option
            v-for="item in dictData[dictIdMaps.orgCls]"
            :key="item.code"
            :label="item.value"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
    </el-row>

    <el-form-item label="区域" class="area clearfix">
      <el-form-item label prop="prov" class="mb0">
        <el-select
          ref="provinceRef"
          v-model="_form.prov"
          filterable
          clearable
          placeholder="请选择省份"
          @change="changeProvince($event)"
        >
          <el-option
            v-for="item in provinceOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label prop="city" label-width="10px" class="mb0">
        <el-select
          ref="cityRef"
          v-model="_form.city"
          filterable
          clearable
          placeholder="请选择市"
          :disabled="_form.prov === ''"
          @change="changeCity($event)"
        >
          <el-option
            v-for="item in cityOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label prop="area" label-width="10px" class="mb0">
        <el-select
          ref="countyRef"
          v-model="_form.area"
          filterable
          clearable
          placeholder="请选择区县"
          :disabled="_form.city === ''"
        >
          <el-option
            v-for="item in countyOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form-item>
    <el-form-item label="详细地址" prop="addr" class="w100">
      <el-input v-model.trim="_form.addr" placeholder="请输入详细地址" type="textarea" :rows="1" />
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {
  computed,
  defineEmits,
  defineExpose,
  defineProps,
  nextTick,
  PropType,
  reactive,
  ref,
  toRefs,
  watch,
} from 'vue'

import { ElMessage } from 'element-plus'

import HoldUpload from '@/components/Upload/index.vue'

import OrgApi from '@/api/backend/organization'

import { useUserStore } from '@/store/user'

import { formatUrl } from '@/utils/common/formatUrl'
import { validate } from '@/utils/formExtend'
import { commonTitleReg } from '@/utils/regExp'
import { useCity } from '&/utils/useCity'

import IBaseObj from '#/index'

const { uid } = useUserStore().userInfo

const rules = {
  name: [
    { required: true, message: '请输入组织名称', trigger: 'blur' },
    { max: 20, message: '输入长度超过20个字符', trigger: 'blur' },
    { ...commonTitleReg, trigger: 'blur' },
  ],
  nameFull: [
    { max: 20, message: '输入长度超过20个字符', trigger: 'blur' },
    { ...commonTitleReg, trigger: 'blur' },
  ],
  type: [{ required: true, message: '请选择组织类型', trigger: 'change' }],
  addr: [{ max: 50, message: '输入长度超过50个字符', trigger: 'blur' }],
  // province: [{ required: true, message: '请选择省份', trigger: 'change' }],
  // city: [{ required: true, message: '请选择市', trigger: 'change' }],
  // county: [{ required: true, message: '请选择区县', trigger: 'change' }],
}

const { cityOptions, countyOptions, getCityOptions, getCountyOptions }: IBaseObj = useCity()

const props = defineProps({
  form: {
    type: Object,
    default: () => {},
  },
  provinceOptions: {
    type: Array as PropType<IBaseObj[]>,
    default: () => [],
  },
  typeOptions: {
    type: Array as PropType<IBaseObj[]>,
    default: () => [],
  },
  dictIdMaps: {
    type: Object as PropType<IBaseObj>,
    default: () => {},
  },
  dictData: {
    type: Object as PropType<IBaseObj>,
    default: () => {},
  },

  isAdd: {
    type: Boolean,
    default: true,
  },
})

const _form: IBaseObj = reactive({
  logo: '',
  name: '',
  cods: '',
  type: '',
  typeOrg: '',
  prov: '',
  city: '',
  area: '',
  addr: '',
})

// watch(
//   () => props.isAdd,
//   (val) => {
//     if (!val) {
//       console.log('ff', _form)
//       _form.prov && getCityOptions(_form.prov)
//       _form.city && getCountyOptions(_form.city)
//     }
//   }
// )

const typeRef = ref()
watch(
  () => _form.type,
  () => {
    nextTick(() => {
      _form.typeOrg = typeRef.value.selectedLabel
    })
  }
)

const state = reactive({
  uploadKey: +new Date(),
})

const { uploadKey } = toRefs(state)

const formRef = ref()
const provinceRef = ref()
const cityRef = ref()
const countyRef = ref()
const changeProvince = (val: string | number) => {
  _form.city = ''
  _form.area = ''
  cityOptions.value = []
  countyOptions.value = []
  nextTick(() => {
    formRef.value.clearValidate(['city', 'area'])
  })

  console.log('v', val)
  if (val) {
    getCityOptions(val)
  }
}
const changeCity = (val: string | number) => {
  countyOptions.value = []
  _form.area = ''
  nextTick(() => {
    formRef.value.clearValidate(['area'])
  })
  if (val) {
    getCountyOptions(val)
  }
}

const editInitCityOptions = (prov: string | number) => {
  if (prov) {
    getCityOptions(prov)
  }
}

const editInitCountyOptions = (city: string | number) => {
  if (city) {
    getCountyOptions(city)
  }
}

const valid = () => validate(formRef.value)
const clear = () => {
  formRef.value.resetFields()
  cityOptions.value = []
  countyOptions.value = []
  delete _form.oid
}

const handleSuccess = (file: any) => {
  console.log('f', file)
  uploadKey.value = +new Date()
  _form.logo = file.file.prepareData
}

defineExpose({
  clear,
  valid,
  form: _form,
  editInitCityOptions,
  editInitCountyOptions,
})
</script>

<style lang="scss" scoped>
.form-drawer .el-form {
  .el-row {
    width: 100%;
  }

  :deep() {
    .el-form-item {
      width: 100%;

      .el-select {
        width: 100%;
      }

      &.area {
        .el-form-item {
          width: 33%;
          &__label {
            font-weight: bold;
          }
        }

        .el-form-item__content {
          display: flex;
          justify-content: space-between;
        }

        .mb0 {
          margin-bottom: 0;
        }
      }

      .el-form-item__content {
        width: auto;
      }
    }

    .cods-item {
      .el-form-item__label {
        line-height: 1.1;
      }
    }
  }
}

.top {
  display: flex;
  justify-content: center;
  width: 100%;

  &-l {
    :deep(.el-form-item__content) {
      width: auto !important;
    }
  }

  &-r {
    margin-left: 10px;
    color: white;
    flex: 1;

    :deep(.el-form-item) {
      width: 100%;

      .el-form-item__content {
        width: auto !important;
      }
    }
  }
}
</style>
